package com.oj.controller;

import com.alibaba.fastjson.JSONObject;
import com.oj.entity.User;
import com.oj.service.UserService;
import com.oj.util.MD5Util;
import com.oj.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Controller
public class KindController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/Kindeditor/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public String uploadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String username = request.getSession().getAttribute("session_username").toString();
        if (username == null || userService.query(username) == null) {
            return getError("Please login first.");
        }

        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        String appPath = jarF.getParentFile().toString();
        String directory = "upload" + File.separator + "file"+ File.separator + username + File.separator + ymd;
        File uploadFileSaveDir = new File(appPath + File.separator + directory);
        if(!uploadFileSaveDir.exists()){
            uploadFileSaveDir.mkdirs();
        }
        String savePath = appPath + File.separatorChar + directory;
        // 定义允许上传的文件扩展名
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");

        // 最大文件大小
        long maxSize = 5 * 1024 * 1024;
        response.setContentType("text/html; charset=UTF-8");
        if (!ServletFileUpload.isMultipartContent(request)) {
            return getError("Please choose file.");
        }

        File uploadDir = new File(savePath);
        // 判断文件夹是否存在,如果不存在则创建文件夹
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        String dirName = request.getParameter("dir");
        if (dirName == null) {
            dirName = "image";
        }
        if (!extMap.containsKey(dirName)) {
            return getError("Unsupport ext " + dirName);
        }

        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = mRequest.getFileMap();
        String fileName = null;
        for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator(); it.hasNext();) {
            Map.Entry<String, MultipartFile> entry = it.next();
            MultipartFile mFile = entry.getValue();
            fileName = mFile.getOriginalFilename();
            // 检查文件大小
            if (mFile.getSize() > maxSize) {
                return getError("Max size " + maxSize + " limit.");
            }
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
                return getError("Unsupport file ext " + fileExt);
            }
            UUID uuid = UUID.randomUUID();
            String path = savePath + uuid.toString() + "." + fileExt;
            BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(path));
            FileCopyUtils.copy(mFile.getInputStream(), outputStream);

            JSONObject obj = new JSONObject();
            obj.put("error", 0);
            obj.put("url", File.separator + directory + uuid.toString() + "." + fileExt);
            return obj.toJSONString();
        }
        return getError("Upload failed...");
    }

    private String getError(String message) {
        JSONObject obj = new JSONObject();
        obj.put("error", 1);
        obj.put("message", message);
        return obj.toJSONString();
    }
}